package com.vesystem.vegua.modules.common.service.impl;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.HexUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.vesystem.vegua.config.GlobalConfig;
import com.vesystem.vegua.config.ServerListener;
import com.vesystem.vegua.exceptionConfig.ErrorCode;
import com.vesystem.vegua.exceptionConfig.ParameterInvalid;
import com.vesystem.vegua.modules.common.controller.RemoteAppController;
import com.vesystem.vegua.modules.common.dto.SysConfigDto;
import com.vesystem.vegua.modules.common.entity.SysAuthorization;
import com.vesystem.vegua.modules.common.mapper.SysAuthorizationMapper;
import com.vesystem.vegua.modules.common.mapper.SysUserMapper;
import com.vesystem.vegua.modules.common.service.ISysAuthorizationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vesystem.vegua.utils.JwtToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hcy
 * @since 2020-12-11
 */
@Service
public class SysAuthorizationServiceImpl extends ServiceImpl<SysAuthorizationMapper, SysAuthorization> implements ISysAuthorizationService {
    private static Logger log = LoggerFactory.getLogger(SysAuthorizationServiceImpl.class);

    @Autowired
    private SysAuthorizationMapper sysAuthorizationMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    public JSONObject getSysAuthorizationInfo(){
        SysAuthorization sysAuthorization = sysAuthorizationMapper.selectById(1);
        try {
            File file = new File(GlobalConfig.BASE_PATH+"secure.hcy");
            byte[] bytes = new byte[16];
            FileInputStream fis = new FileInputStream(file);
            fis.read(bytes);
            fis.close();
            AES aes = SecureUtil.aes(bytes);
            byte[] decrypt = aes.decrypt(HexUtil.decodeHex(sysAuthorization.getAuthorization()));
            String jsonStr = new String(decrypt,"UTF-8");
            JSONObject r_json = JSONUtil.parseObj(jsonStr);
            r_json.set("machineCode", HexUtil.encodeHexStr(bytes));
            return r_json;
        } catch (FileNotFoundException e) {
            log.error(e.getLocalizedMessage(),e);
        } catch (IOException e) {
            log.error(e.getLocalizedMessage(),e);
        }
        throw new ParameterInvalid(ErrorCode.UNKNOWN_ERROR);
    }

    public void updateSysAuthorizationInfo(MultipartFile file){
        String fileId = Long.toString(System.currentTimeMillis());
        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring( fileName.lastIndexOf(".") );
        File licence = new File(GlobalConfig.BASE_PATH +
                GlobalConfig.BASE_PATH_ABOUT_OTHER +fileId +suffixName  );
        if ( !licence.exists() ){
            try {
                licence.createNewFile();
                file.transferTo(licence);
                BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(licence)));
                String signInfo =  br.readLine();
                br.close();
                File secure_file = new File(GlobalConfig.BASE_PATH+"secure.hcy");
                byte[] bytes = new byte[16];
                FileInputStream fis = new FileInputStream(secure_file);
                fis.read(bytes);
                fis.close();
                AES aes = SecureUtil.aes(bytes);
                byte[] decrypt = aes.decrypt(HexUtil.decodeHex(signInfo));
                String aa = new String(decrypt);
                JSONObject sign = JSONUtil.parseObj(aa);
                Integer userNum = sysUserMapper.selectCount(new QueryWrapper<>());
                if ( sign.getInt("maxUser").intValue()+ ServerListener.SYSTEM_ACCOUNT_NUM  < userNum  ){
                    throw new ParameterInvalid(ErrorCode.THE_NUMBER_OF_LICENSE_USERS_IS_TOO_SMALL);
                }
                ServerListener.SIGN.setOrg(sign.getStr("org"));
                ServerListener.SIGN.setMaxUser(sign.getInt("maxUser"));
                ServerListener.SIGN.setExpiration(sign.getLong("expiration"));
                sysAuthorizationMapper.updateById(new SysAuthorization(1,signInfo));
            } catch (IOException e) {
                log.error(e.getLocalizedMessage(),e);
            }
        }

    }

    @Deprecated // 系统配置请使用 nacos 统一管理
    public List<SysConfigDto> getSysConfigDtoList(){
        List<SysConfigDto> list = new ArrayList<>();
        SysConfigDto c1 = new SysConfigDto("PROXY_IP",GlobalConfig.PROXY_IP,true,"gua网关服务器ip");
        list.add(c1);
        SysConfigDto c2 = new SysConfigDto("PROXY_PORT",GlobalConfig.PROXY_PORT.toString(),true,"gua网关服务器端口");
        list.add(c2);
        SysConfigDto c3 = new SysConfigDto("BASE_PATH",GlobalConfig.BASE_PATH,false,"基础文件路径,该路径在系统正式运行后不应该被修改");
        list.add(c3);
        SysConfigDto c4 = new SysConfigDto("INIT_PWD",GlobalConfig.INIT_PWD,true,"用户的初始化密码");
        list.add(c4);
        SysConfigDto c5 = new SysConfigDto("PROXY_RDP_SECURITY",GlobalConfig.PROXY_RDP_SECURITY,false,"RDP连接的安全模式");
        list.add(c5);
        SysConfigDto c6 = new SysConfigDto("EXTEND_UAM_CHECK_TOKEN_URL",GlobalConfig.EXTEND_UAM_CHECK_TOKEN_URL,true,"和uam企业版对接时token有效性校验地址");
        list.add(c6);
        return list;
    }


}
